package com.qinggeng.project.system.service.impl;

import com.qinggeng.common.enums.MemberEnum;
import com.qinggeng.common.enums.MemberTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.project.system.domain.*;
import com.qinggeng.project.system.dto.MemberDTO;
import com.qinggeng.project.system.mapper.*;
import com.qinggeng.project.system.service.ISysConfigService;
import com.qinggeng.project.system.service.ISysUserService;
import com.qinggeng.project.system.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.security.acl.LastOwnerException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private IMemberMapper memberMapper;


    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrdersGoodsMapper ordersGoodsMapper;


    @Autowired
    private ISysConfigService sysConfigService;


    @Autowired
    private ISysUserService userService;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Integer isMember(Long userId,Integer type) {
        Member member=getMember(userId,type);
        if (member==null){
            return MemberEnum.NOT_MEMBER.getKey();
        }
        Integer status=member.getStatus();
        if (status!=0){
            return MemberEnum.MEMBER_DISABLE.getKey();
        }
        //获取当前时间戳
        Instant instant = Instant.now();
        long timeStampMillis = instant.toEpochMilli();
        //数据库时间 购买会员时间
        Long  expireStamp=member.getExpireStamp();
        //当前时间戳 >=  购买会员时间
        if (timeStampMillis>=expireStamp){
            return MemberEnum.MEMBER_EXPIRED.getKey();
        }
        return MemberEnum.MEMBER.getKey();
    }

    @Override
    public Integer isVip(Long userId) {
        return isMember( userId, MemberTypeEnum.VIP_MEMBER.getKey());
    }

    @Override
    public Integer isSVip(Long userId) {
         return isMember( userId,MemberTypeEnum.SVIP_MEMBER.getKey());
    }

    @Override
    public Member getMember(Long userId,Integer type) {
        if (null ==userId){
            throw  new CustomException("userId is null");
        }
        Example example=new Example(Member.class);
        example.setOrderByClause(" id  desc limit 1");
        example.createCriteria()
                .andEqualTo("userId",userId)
                .andEqualTo("type",type)
                .andEqualTo("isDelete",0);
        Member member=memberMapper.selectOneByExample(example);
        return member;
    }

    @Override
    public boolean insertMember(MemberDTO dto) {
        Long userId=dto.getUserId();
        if (null ==userId){
            throw  new CustomException("userId is null");
        }
        String phonenumber=dto.getPhonenumber();
        if (StringUtils.isEmpty(phonenumber)){
            throw  new CustomException("phonenumber is null");
        }
        Member m=new Member();
        m.setUserId(userId);
        Date date=new Date();
        m.setCreateTime(date);
        m.setUpdateTime(date);
        m.setStartTime(date);
        Date endTime= dto.getEndTime();
        if (null==endTime){
            throw  new CustomException("endTime is null");
        }
        m.setEndTime(endTime);
        m.setExpireStamp(endTime.toInstant().toEpochMilli());
        m.setPhonenumber(phonenumber);
        m.setType(dto.getVipType());
        m.setStatus(0);
        m.setIsDelete(0);
        return memberMapper.insertSelective(m)>0;
    }

    @Override
    public List<Member> listMember(MemberDTO dto) {
        Example example=new Example(Member.class);
        example.setOrderByClause(" id  desc");
        return memberMapper.selectByExample(example);
    }

    @Override
    public boolean buyVip(String orderNo) {
       Orders orders= ordersMapper.selectOrdersByOrdersNo(orderNo);
       if (orders==null){
           return  true;
       }
       Long userId= orders.getUserId();
       SysUser user=userService.selectUserById(userId);
       Long ordersId= orders.getOrdersId();
        List<OrdersGoods> list=  ordersGoodsMapper.selectOrderGoodListByOrdersId(ordersId);
        if (null==list||list.isEmpty()){
            log.info("验证会员产品是空 orderNo {}",orderNo);
            return false;
        }
        if (list.size()!=1){
            log.info("验证会员产品数量 orderNo {}",orderNo);
            return false;

        }
        String goodsIds=(String) sysConfigService.selectConfigByKey("sys.vip");
        String[] ids=goodsIds.split(",");
        OrdersGoods ordersGoods=list.get(0);
        Long goodsId=ordersGoods.getGoodsId();
        for (int j = 0; j < ids.length; j++) {
                String id=ids[j];
            if (String.valueOf(goodsId).equals(id)){
                Goods goods= goodsMapper.selectGoodsById(goodsId);
                MemberDTO memberDTO=new MemberDTO();
                memberDTO.setUserId(userId);
                memberDTO.setPhonenumber(user.getPhonenumber());
                LocalDate localDate=LocalDate.now();
                localDate.plus(Integer.valueOf(goods.getAttributesName()), ChronoUnit.MONTHS);
                ZoneId zone = ZoneId.systemDefault();
                Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
                java.util.Date endDate = Date.from(instant);
                memberDTO.setEndTime(endDate);
                boolean bl= insertMember(memberDTO);
                if (bl){
                    return  true;
                }
            }
        }
        throw  new CustomException("会员购买出错 orderNo "+orderNo);
    }
}
